package com.example.homework.adapters

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.example.homework.api.MarsPhotosService
import com.example.homework.models.Photo

class PhotosPagingSource : PagingSource<Int, Photo>() {
    override fun getRefreshKey(state: PagingState<Int, Photo>): Int = FIRST_PAGE

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Photo> {
        val page = params.key ?: FIRST_PAGE
        return kotlin.runCatching {
            MarsPhotosService.getPhotos(page)
        }.fold(
            onSuccess = {
                LoadResult.Page(
                    data = it,
                    prevKey = null,
                    nextKey = if (it.isEmpty()) null else page + 1
                )
            },
            onFailure = {
                LoadResult.Error(it)
            }
        )
    }

    companion object {
        const val FIRST_PAGE: Int = 0
    }
}